package com.atxiaodei.html2pdf.demos.web;

import io.woo.htmltopdf.HtmlToPdf;
import io.woo.htmltopdf.HtmlToPdfObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;

/**
 * @ClassName DemoController
 * @Description TODO
 * @Author wangmeng
 * @Date 2024/1/8 15:48
 * @Version 1.0
 **/
@RestController
public class DemoController {

    @GetMapping("/htmltopdf")
    public String htmltopdf() throws Exception {

        StringBuffer head = readTxtFileInResources("html/demo1");


        HtmlToPdf.create()
                .object(HtmlToPdfObject.forHtml(head.toString()).defaultEncoding("utf8"))
                .convert("E:\\pdfdemo\\demo.pdf");

        return "htmltopdf";
    }




    private StringBuffer readTxtFileInResources(String relPath) {
        StringBuffer sb = new StringBuffer();

        try (InputStream fileIs = this.getClass().getClassLoader().getResourceAsStream(relPath)) {
            final int maxSize = 1024;
            byte[] buff = new byte[maxSize];
            int read = 0;

            while ((read = fileIs.read(buff, 0, maxSize)) > 0) {
                sb.append(new String(buff, 0, read));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return sb;
    }

}
